package com.example.common.email;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * @author 陈建峰
 * @date 2022/11/2 14:33
 * @Description
 */
@Service
public class EmailService {

    @Autowired
    private JavaMailSender javaMailSender;
    //发送人和配置文件中一致
    private String from = "3442748294@qq.com";
//    //接收人
//    private String to = "test@126.com";
//    //标题
//    private String subject = "测试邮件";
//    //正文
//    private String context = "测试邮件正文内容：我想给陈老老老板一键三连";

    /**
     * 发送简单邮箱
     *
     * @param to      给谁发
     * @param subject 标题
     * @param context 正文
     */
    public void sendMail(String to, String subject, String context) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(context);
        javaMailSender.send(message);
    }


    /**
     * 发送复杂的邮件
     *
     * @param to
     * @param subject
     * @param context
     */
    public void sendHtmlMail(String to, String subject, String context) {
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message);
            helper.setTo(to);
            helper.setFrom(from);
            helper.setSubject(subject);
            //此处设置正文支持html解析
            helper.setText(context, true);

            javaMailSender.send(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送带有附件的邮箱
     *
     * @param to
     * @param subject
     * @param context
     * @param file
     */
    public void sendMail(String to, String subject, String context, File file) {
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            //此处设置支持附件
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(context);

            //添加附件
//            File f1 = new File("springboot_mail-0.0.1-SNAPSHOT.jar");
//            File f2 = new File("resources\\logo.png");

            helper.addAttachment(file.getName(), file);
//            helper.addAttachment("陈老老老板",f2);

            javaMailSender.send(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
